<?php
class Notice_Email 
{
	private $_subject, $_message, $_to, $_cc, $sender;
	private $_attachments = array();

	public function __construct ()
	{
		$this->_cc = array();
	}

	public function to ($to)
	{
		$this->_to = (string) $to;
		return $this;
	}

	public function cc ($cc)
	{
		$this->_cc[] = (string) $cc;
		return $this;
	}

	public function subject ($subject)
	{
		$this->_subject = $subject;
		return $this;
	}

	public function message ($message)
	{
		$this->_message = (string) $message;
		return $this;
	}

	public function attachment ($filepath)
	{
		$this->_attachments[] = $filepath;
		return $this;
	}

	public function sender($name)
	{
		$this->_sender = (string) $name;
		return $this;
	}

	/* 
	 * 发送邮件
	 *
	 * @param	string	$message : 邮件正文 (utf-8)编码
	 * @return	boolean
	 */
	public function send ($message = NULL)
	{
		if (! empty($message))
			$this->_message = (string) $message;

		return $this->do_send();
	}

	protected function mail_from ()
	{
		//$suffix  = 'noreply';
		//$prefix  = 'sohuaijia';
		//$rand    = uniqid();
		//$address = "{$prefix}-{$rand}-{$suffix}@appchina.com";
		//$address = 'no-reply@appchina.com';
                $address = 'service@mail.wayatrip.com';

		return $address;
	}

	protected function do_send ()
	{
		require_once (DOCROOT . 'modules/notice/classes/PHPMailer/class.phpmailer.php');
		$mail = new PHPMailer(true); 
		$mail->IsSMTP(); 
		$smtp = Kohana::config('notice.email.smtp');

		try {


		$mail->Host       = $smtp['host']; // SMTP server
		$mail->CharSet    = 'UTF-8';
		$mail->SMTPDebug  = 0;
		$mail->Port       = $smtp['port'];
		if (empty($this->_sender))
		{
		    $this->_sender = Kohana::config('notice.email.sender.name');
		}
		if (!empty($smtp['auth']))
		{
		    $mail->SMTPAuth = true;
		    $mail->Username = $smtp['user'];
		    $mail->Password = $smtp['pass'];
		    $mail->SetFrom($smtp['user'], $this->_sender);
		}
		else 
		{
		    $mail->SMTPAuth = false;
		    $mail->SetFrom($this->mail_from(), $this->_sender);
		}
		$mail->AddAddress($this->_to);
		if (! empty($this->_cc))
		{
			foreach ($this->_cc as $addr)
				$mail->AddCC($addr);
		}
		$mail->Subject    = $this->_subject;
		$mail->isHTML(TRUE);
		$mail->Body       = $this->_message;

		if (!empty($this->_attachments))
		{
			foreach ($this->_attachments as $fp)
				$mail->AddAttachment($fp);
		}

		$mail->Send();

		} 
		catch (Exception $e) 
		{
			return FALSE;
		}

		return TRUE;
	}
}
